cc.Class({
    extends: cc.Component,

    properties: {
        manifestUrl: {
            default: null,
            url: cc.RawAsset
        }
    },

    checkCb: function (event) {
        cc.log('check version code: ' + event.getEventCode());
        this.load._stateStr ='检查资源更新';
        switch (event.getEventCode())
        {
            case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
                console.log("No local manifest file found, hot update skipped.");
                cc.eventManager.removeListener(this._checkListener);
                this.load.startPreloading();
                break;
            case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
            case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
                console.log("Fail to download manifest file, hot update skipped.");
                cc.eventManager.removeListener(this._checkListener);
                this.load.startPreloading();
                break;
            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
                console.log("Already up to date with the latest remote version.");
                cc.eventManager.removeListener(this._checkListener);
                this.load._stateStr ='版本最新，启动游戏  ';
                //启动游戏
                this.load.startPreloading();
               // cc.director.loadScene("loading");
                break;
            case jsb.EventAssetsManager.NEW_VERSION_FOUND:
                this._needUpdate = true;
                cc.eventManager.removeListener(this._checkListener);
                this.hotUpdate();
                break;
            default:
                break;
        }
        
    },


    checkUpdate: function () {
       
        this._checkListener = new jsb.EventListenerAssetsManager(this._am, this.checkCb.bind(this));
        cc.eventManager.addListener(this._checkListener, 1);
        //开始检查版本，回调监听为checkcb
        this._am.checkUpdate();
       
    },

    updateCb: function (event) {
        var needRestart = false;
        var failed = false;
        switch (event.getEventCode())
        {
            case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
                console.log('No local manifest file found, hot update skipped.');
                failed = true;
                break;
            case jsb.EventAssetsManager.UPDATE_PROGRESSION:

                var assetId = event.getAssetId();
                
                if(assetId == "@version"){
                    //版本文件
                    console.log("热更新检查版本文件 version.manifest ...");
                    break;

                }
                if(assetId == '@manifest'){
                    //projuect文件
                    console.log("热更新检查版本文件 project.manifest...");
                    break;
                }
                 var percent = event.getPercent() ;

                if(isNaN(percent)){ 
                    console.log("热更新非法数字");
                     break;
                }
                percent=percent.toFixed(2);
                if(!this.load._isLoading){
                     this.load._isLoading =true;
                      this.load._stateStr ='正在更新游戏资源  ';
                }
                console.log("热更新字节进度:"+percent + '%');
                this.load._progress=percent;
               
                break;
            case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
            case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST:
                console.log('Fail to download manifest file, hot update skipped.');
                failed = true;
                break;
            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE:
                console.log('Already up to date with the latest remote version.');
                failed = true;
                break;
            case jsb.EventAssetsManager.UPDATE_FINISHED:
                console.log('Update finished. ' + event.getMessage());
                
                needRestart = true;
                this.load._isLoading =false;
                
                break;
            case jsb.EventAssetsManager.UPDATE_FAILED:
                console.log('Update failed. ' + event.getMessage());

                this._failCount ++;
                if (this._failCount < 2)
                {
                    this._am.downloadFailedAssets();
                }
                else
                {
                    console.log('Reach maximum fail count, exit update process');
                    this._failCount = 0;
                    failed = true;
                }
                break;
            case jsb.EventAssetsManager.ERROR_UPDATING:
                console.log('Asset update error: ' + event.getAssetId() + ', ' + event.getMessage());
                break;
            case jsb.EventAssetsManager.ERROR_DECOMPRESS:
                console.log(event.getMessage());
                break;
            default:
                break;
        }

        if (failed) {
            cc.eventManager.removeListener(this._updateListener);
            this.load._stateStr  =  '游戏更新失败..';
            this.load._isLoading =false;
            this.load._progress=0.0;
            //更新失败 删除文件 重新更新
            var storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : '/') + 'paijiu-asset');
            jsb.fileUtils.removeDirectory(storagePath);
            cc.sys.localStorage.setItem('HotUpdateSearchPaths', null);
            cc.game.restart();
        }

        if (needRestart) {
            cc.eventManager.removeListener(this._updateListener);
            // Prepend the manifest's search path
            var searchPaths = jsb.fileUtils.getSearchPaths();
            var newPaths = this._am.getLocalManifest().getSearchPaths();
            Array.prototype.unshift(searchPaths, newPaths);
            // This value will be retrieved and appended to the default search path during game startup,
            // please refer to samples/js-tests/main.js for detailed usage.
            // !!! Re-add the search paths in main.js is very important, otherwise, new scripts won't take effect.
            cc.sys.localStorage.setItem('HotUpdateSearchPaths', JSON.stringify(searchPaths));

            jsb.fileUtils.setSearchPaths(searchPaths);
            console.log( "游戏资源更新完毕重启");
            this.load._stateStr ='游戏资源更新完毕重启';
            cc.game.restart();
        }
    },

    hotUpdate: function () {
        if (this._am && this._needUpdate) {
            this._updateListener = new jsb.EventListenerAssetsManager(this._am, this.updateCb.bind(this));
            cc.eventManager.addListener(this._updateListener, 1);
           
            this._failCount = 0;
            this._am.update();
            
        }
    },

    // use this for initialization
    init: function (loadingLogic) {
        // Hot update is only available in Native build
     this.load= this.node.getComponent('LoadingLogic');
     if(!this.load){
         console.log('LoadingLogic is not exist..');
         return;
     }
        if (!cc.sys.isNative) {
            return;
        }


        var storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : '/') + 'paijiu-asset');
        cc.log('Storage path for remote asset : ' + storagePath);
        cc.log('Local manifest URL : ' + this.manifestUrl);
       
        this._am = new jsb.AssetsManager(this.manifestUrl, storagePath);
        this._am.retain();

        this._needUpdate = false;
        
       cc.log('检查是否需要更新 ');
        if (this._am.getLocalManifest().isLoaded())
        {
            //开始更新
            this.checkUpdate();
        }else{
            this.load.startPreloading();
        }
    },

    onDestroy: function () {
        this._am && this._am.release();
    }
});

